﻿using System;
using System.Globalization;
using System.IO;
using QDT.CFCA;
using QDT.Common;
using QDT.Common.Data;
using QDT.Core;
using QDT.Core.Projects;

namespace QDT.Web.Admin.Code
{
    public class PDFSealToo
    {
        protected PDFSealFunction Service = IoC.Resolve<PDFSealFunction>();

        public void SeaProjectAgreement(int pid)
        {
            var db = IoC.Resolve<IUnitOfWork>() as IDbProvider;
            if (db == null) throw new Exception("数据库连接异常");
            var project = db.GetByID<Project>(pid);

            var fileName = Guid.NewGuid() + ".pdf";
            var ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
            var basePath = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["FileSavePath"]);
            var pdfPath = basePath + "{0}\\".FormatWith("pdf") + ymd + "\\";
            var sealPath = basePath + "{0}\\".FormatWith("agreement") + ymd + "\\";

            if (!Directory.Exists(pdfPath)) Directory.CreateDirectory(pdfPath);
            if (!Directory.Exists(sealPath)) Directory.CreateDirectory(sealPath);

            pdfPath += fileName;
            sealPath += fileName;

            try
            {
                Service.ConvertWebToPdf(project.ID, pdfPath);
                var file = Utils.ReadFile(pdfPath);
                var seal = Service.SealByProjectAgency(file, project.Parent.AgencyId);
                File.WriteAllBytes(sealPath, seal);
                project.AgreementLink = sealPath;
                db.SaveChanges();
            }
            catch (Exception exception)
            {
                throw new Exception(exception.Message);
            }
        }

    }
}